<template>
  <div ref="chartRef" class="chart-container"></div>
</template>

<script setup>
import { onMounted, onUnmounted, ref, watch, defineProps } from 'vue';
import * as echarts from 'echarts';

const props = defineProps({
  values: {
    type: Array,
    default: () => []
  }
});

const chartRef = ref(null);
const chartInstance = ref(null);

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;

  // 销毁旧实例（如果存在）
  if (chartInstance.value) {
    chartInstance.value.dispose();
  }

  // 创建新实例
  chartInstance.value = echarts.init(chartRef.value);

  // 设置基础配置（不包含数据）
  const baseOption = {
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      axisTick: {
        alignWithLabel: true
      },
      axisLabel: {
        color: '#666'
      },
      axisLine: {
        lineStyle: {
          color: '#103b56'
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        color: '#666'
      },
      axisLine: {
        lineStyle: {
          color: '#ccc'
        }
      },
      splitLine: {
        show: false
      }
    },
    series: [
      {
        name: '能源消耗',
        type: 'bar',
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 1,
                color: '#103b56'
              },
              {
                offset: 0,
                color: '#3bebf1'
              }
            ]
          },
          borderRadius: [8, 8, 0, 0]
        },
        barWidth: '60%'
      }
    ]
  };

  // 应用基础配置
  chartInstance.value.setOption(baseOption);

  // 更新数据
  updateChartData();

  // 监听窗口大小变化，调整图表
  window.addEventListener('resize', handleResize);
};

// 仅更新图表数据
const updateChartData = () => {
  console.log(9)
  if (!chartInstance.value) return;

  // 准备需要更新的数据
  const dataOption = {
    xAxis: {
      data: props.values.slice(0,5).map((_, index) => String(index + 2021))
    },
    series: [
      {
        data: props.values
      }
    ]
  };

  // 使用setOption更新数据，不影响其他配置
  chartInstance.value.setOption(dataOption);
};

// 处理窗口大小变化
const handleResize = () => {
  if (chartInstance.value) {
    chartInstance.value.resize();
  }
};

// 组件挂载时初始化图表
onMounted(() => {
  initChart();
});

// 监听props.values变化，只更新数据
watch(
  () => props.values,
  () => {
    updateChartData();
  },
  { deep: true }
);

// 组件卸载时清理资源
onUnmounted(() => {
  if (chartInstance.value) {
    chartInstance.value.dispose();
    window.removeEventListener('resize', handleResize);
  }
});
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 400px;
  background-color: transparent;
}
</style>